package com.yimidida.library.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yimidida.library.R;
import com.yimidida.library.utils.LogUtils;
import com.yimidida.library.utils.NavigationBarUtil;
import com.yimidida.library.utils.ProgressDialogUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Create on: 9/14/21
 * by Mr.Zhu
 * Description: 基类activity
 */
public abstract class BaseActivity<V extends BaseView, T extends BasePresenter<V>> extends AppCompatActivity implements BaseView {

    protected T mPresenter;//presenter实例
    public RelativeLayout rootView;
    private TextView titleTv;
    private TextView leftTv;
    private ImageView rightIm1;
    private ImageView rightIm2;
    private TextView rightTv;
    private RelativeLayout tooBarLayout;
    private View toBarLayout;
    private FrameLayout contentContainer;//子类布局
    private View viewLine;
    private View contentView;
    private Handler handler = new Handler();
    private LoadingDialog loadingDialog;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateTime();
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        rootView = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
        toBarLayout = (View) rootView.findViewById(R.id.titleLayout);
        tooBarLayout = (RelativeLayout) rootView.findViewById(R.id.RL_tooBarLayout);
        contentContainer = (FrameLayout) rootView.findViewById(R.id.contentContainer);
        titleTv = (TextView) rootView.findViewById(R.id.text_title);
        leftTv = (TextView) rootView.findViewById(R.id.tv_left);
        rightTv = (TextView) rootView.findViewById(R.id.tv_right);
        viewLine = (View) rootView.findViewById(R.id.view_line);
        rightIm1 = rootView.findViewById(R.id.im_right1);
        rightIm2 = rootView.findViewById(R.id.im_right2);
        toBarLayout.setVisibility(View.GONE);
        leftTv.setVisibility(View.GONE);
        mPresenter = initPresenter();
        if (mPresenter != null) {
            mPresenter.attach((V) this);
        }
        loadingDialog = new LoadingDialog(this);
        initApp();
        hideBottomUIMenu();
    }


    public void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setTextviwDrawable(leftTv, getDrawable(R.mipmap.back_black), null, null, null);
            }
//            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setTextviwDrawable(leftTv, getDrawable(R.mipmap.back_white), null, null, null);
            }
//            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }


    public void setTextviwDrawable(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom) {
        if (left != null) {
            left.setBounds(0, 0, NavigationBarUtil.dpToPx(40), NavigationBarUtil.dpToPx(40));// 设置图片宽高
        }
        if (top != null) {
            top.setBounds(0, 0, top.getMinimumWidth(), top.getMinimumHeight());// 设置图片宽高
        }

        if (right != null) {
            right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());// 设置图片宽高
        }

        if (bottom != null) {
            bottom.setBounds(0, 0, bottom.getMinimumWidth(), bottom.getMinimumHeight());// 设置图片宽高
        }
        textView.setCompoundDrawables(left, top, right, bottom);// 设置到控件中
    }

    public void setViewLineVisable(boolean visable) {
        if (visable) {
            viewLine.setVisibility(View.VISIBLE);
        } else {
            viewLine.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public void setContentView(int layoutResID) {
        contentView = LayoutInflater.from(this).inflate(layoutResID, null);
        contentContainer.addView(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        super.setContentView(rootView);
    }

    /**
     * 沉浸式实现
     *
     * @param StatusBarHide 是否沉浸式
     * @param VISIBLEBAR    是否显示状态栏
     */
    protected void setStatusBar(boolean StatusBarHide, boolean VISIBLEBAR) {
//        if (StatusBarHide) {
//            transparencyBar(this);
//        }
        if (VISIBLEBAR) {
            toBarLayout.setVisibility(View.VISIBLE);
        } else {
            toBarLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 沉浸式实现
     *
     * @param StatusBarHide 是否沉浸式
     * @param VISIBLEBAR    是否显示状态栏
     * @param colorId       背景颜色
     */
    protected void setStatusBar(boolean StatusBarHide, boolean VISIBLEBAR, int colorId) {
//        if (StatusBarHide) {
//            transparencyBar(this);
//        }
        if (VISIBLEBAR) {
            toBarLayout.setVisibility(View.VISIBLE);
        }
        if (toBarLayout != null && colorId != 0) {
            toBarLayout.setBackgroundColor(getResources().getColor(colorId));
        }
    }

    public void setLeftTvOnclick(View.OnClickListener clickListener) {
        leftTv.setOnClickListener(clickListener);
        leftTv.setVisibility(View.VISIBLE);
    }

    public void setLeftTv(String name, int res) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setTextviwDrawable(leftTv, getDrawable(res), null, null, null);
        }
        leftTv.setText(name);
        leftTv.setVisibility(View.VISIBLE);
    }

    public void setLeftTv(String name, int res, View.OnClickListener clickListener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setTextviwDrawable(leftTv, getDrawable(res), null, null, null);
        }
        leftTv.setText(name);
        leftTv.setOnClickListener(clickListener);
        leftTv.setVisibility(View.VISIBLE);
    }


    /**
     * 沉浸式实现
     *
     * @param StatusBarHide 是否沉浸式
     * @param VISIBLEBAR    是否显示状态栏
     * @param clickListener 返回键监听
     */
    protected void setStatusBar(boolean StatusBarHide, boolean VISIBLEBAR, View.OnClickListener clickListener) {
//        if (StatusBarHide) {
//            transparencyBar(this);
//        }
        if (VISIBLEBAR) {
            toBarLayout.setVisibility(View.VISIBLE);
        }
        leftTv.setOnClickListener(clickListener);
        leftTv.setVisibility(View.VISIBLE);
    }

    @Override
    public void setTitle(CharSequence title) {
        titleTv.setText(title);
    }

    public void setTitle(CharSequence title, int textColor) {
        titleTv.setText(title);
        if (textColor != 0) {
            titleTv.setTextColor(getResources().getColor(textColor));
        }
    }


    @Override
    public void setTitle(int titleId) {
        String titleStr = getResources().getString(titleId);
        titleTv.setText(titleStr);
    }

    public void setTitle(Drawable drawable) {
        titleTv.setBackground(drawable);
    }

    public void setRight1Image(int resourse, View.OnClickListener onClickListener) {
        if (onClickListener != null) {
            rightIm1.setOnClickListener(onClickListener);
        }
        setRightImage1Resourse(resourse);
    }


    public void setRight2Image(int resourse, View.OnClickListener onClickListener) {
        if (onClickListener != null) {
            rightIm2.setOnClickListener(onClickListener);
        }
        setRightImage2Resourse(resourse);
    }

    public void setRightImage1Resourse(int resourse) {
        rightIm1.setImageResource(resourse);
    }

    public void setRightImage2Resourse(int resourse) {
        rightIm2.setImageResource(resourse);
    }

    public void setRightTvText(String text, View.OnClickListener clickListener) {
        rightTv.setText(text);
        rightTv.setOnClickListener(clickListener);
    }


    public void setRightTvText(String text, int textColor, View.OnClickListener clickListener) {
        rightTv.setText(text);
        rightTv.setOnClickListener(clickListener);
        if (textColor != 0) {
            rightTv.setTextColor(getResources().getColor(textColor));
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setRightTvText(String text, int resId, int textColor, View.OnClickListener clickListener) {
        rightTv.setText(text);
        rightTv.setOnClickListener(clickListener);
        if (resId != 0) {
            setTextviwDrawable(rightTv, null, null, getDrawable(resId), null);
        }
        if (textColor != 0) {
            rightTv.setTextColor(getResources().getColor(textColor));
        }
    }

    public TextView getRightTv() {
        return rightTv;
    }


    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.getInstance().showLog("RUNACTIVITY", getLocalClassName());
        hideBottomUIMenu();
    }

    private void initApp() {
        updateTime();
        handler.postDelayed(runnable, 1000);
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        NavigationBarUtil.hideNavigationBar(getWindow());
    }

    private void updateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String currentTime = sdf.format(new Date());
        rightTv.setText(currentTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }

    //初始化presenter
    protected abstract T initPresenter();

    protected abstract void initView();


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
//            case RequestCode.READ_PHONE_STATE: //读取设备信息
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    InitLogical.getInstance().initAPP(this);
//                } else {
//                    ToastUtils.show("请授予权限，否则无法正常使用");
//                }
//                break;
        }
    }

    public void showConfirmCancelDialog(String title, String content, final ICallBackListener listener) {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        normalDialog.setTitle(title);
        normalDialog.setMessage(content);
        normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (listener != null) listener.onCallBack();
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        normalDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (normalDialog != null) {
                    dialog.dismiss();
                }
            }
        });
        // 显示
        if (this != null && !this.isFinishing()) {
            normalDialog.show();
            normalDialog.setCancelable(false);
        }
    }


    public void showLoading(String text) {
        loadingDialog.showLoading();
    }

    public void showLoading(String text, int dismissTime) {
        ProgressDialogUtils.showProgressDialog(this, text, dismissTime);
    }

    public void showLoading() {
        ProgressDialogUtils.showProgressDialog(this, "正在努力加载中", 3000);
    }

    public void hideLoading() {
        loadingDialog.dismiss();
    }

    public void showLoading(String text, int disMissTime, ICallBackResultListener respCallBackListener) {
        ProgressDialogUtils.showProgressDialog(this, text, disMissTime, respCallBackListener);
    }

    public void showLoading(String text, ICallBackResultListener respCallBackListener) {
        ProgressDialogUtils.showProgressDialog(this, text, 2000, respCallBackListener);
    }


}
